package udp;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpSender {

    public static void main(String[] args) {
        //声明数据报
        DatagramPacket dp = null;
        //声明数据包套接字
        DatagramSocket ds = null;
        Scanner input = new Scanner(System.in);
        byte[] buf = new byte[1024];
        try {
            ds = new DatagramSocket();
            while(true){
                String massage = input.nextLine();
                byte[] data = massage.getBytes();
                dp = new DatagramPacket(data,data.length, InetAddress.getByName("localhost"),8989);
                ds.send(dp);
                if (massage.equals("bye")) {
                    break;
                }
                dp = new DatagramPacket(buf,buf.length);
                ds.receive(dp);
                massage = new String(dp.getData(),0,dp.getLength());
                System.out.println("服务器说：" + massage);
            }
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            ds.close();
        }
    }
}
